package com.fxd.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fxd.core.enums.AttrTypeEnum;
import com.fxd.core.util.KeyUtils;
import com.fxd.core.util.PageUtils;
import com.fxd.core.util.Query;
import com.fxd.model.product.AttrAttrgroupRelationEntity;
import com.fxd.model.product.AttrEntity;
import com.fxd.model.product.AttrGroupEntity;
import com.fxd.model.product.CategoryEntity;
import com.fxd.shopping.product.dao.AttrAttrgroupRelationDao;
import com.fxd.shopping.product.dao.AttrDao;
import com.fxd.shopping.product.dao.AttrGroupDao;
import com.fxd.shopping.product.dao.CategoryDao;
import com.fxd.shopping.product.dto.AttrInfoDTO;
import com.fxd.shopping.product.dto.AttrListDTO;
import com.fxd.shopping.product.param.AttrGroupRelationDelAndAddParam;
import com.fxd.shopping.product.param.AttrSaveParam;
import com.fxd.shopping.product.service.AttrService;
import com.fxd.shopping.product.service.CategoryService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrSaveParam attr) {
        //保存基础数据
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        if (attr.getAttrType() == AttrTypeEnum.BAEE.getValue()) {
            //保存关联关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationDao.insert(relationEntity);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? AttrTypeEnum.BAEE.getValue() : AttrTypeEnum.SALE.getValue());
        if (catelogId != 0) {
            wrapper.eq("catelog_Id", catelogId);
        }
        String key = KeyUtils.getKey(params);
        if (StringUtils.isNotBlank(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        List<AttrListDTO> attrListDTOS = page.getRecords().stream().map((attrEntity) -> {
            AttrListDTO attrListDTO = new AttrListDTO();
            BeanUtils.copyProperties(attrEntity, attrListDTO);
            if ("base".equalsIgnoreCase(attrType)) {
                //封装分类和分组的名称
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                Long attrGroupId = null;
                if (relationEntity != null) {
                    attrGroupId = relationEntity.getAttrGroupId();
                }
                if (attrGroupId != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    attrListDTO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrListDTO.setCatelogName(categoryEntity.getName());
            }
            return attrListDTO;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrListDTOS);
        return pageUtils;
    }

    @Override
    public AttrInfoDTO getAttrInfo(Long attrId) {

        AttrInfoDTO attrInfoDTO = new AttrInfoDTO();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrInfoDTO);

        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (attrEntity.getAttrType() == AttrTypeEnum.BAEE.getValue()) {
            //获取分组信息
            if (relationEntity != null) {
                attrInfoDTO.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrInfoDTO.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        //获取分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrInfoDTO.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            attrInfoDTO.setCatelogName(categoryEntity.getName());
        }

        return attrInfoDTO;
    }

    @Override
    public void updateAttr(AttrSaveParam attr) {
        //保存基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attrEntity.getAttrType() == AttrTypeEnum.BAEE.getValue()) {
            //修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id找到关联的所有基本属性
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = relationEntities.stream().map((relationEntity) -> {
            return relationEntity.getAttrId();
        }).collect(Collectors.toList());

        Collection<AttrEntity> attrEntities = null;
        if (CollectionUtils.isNotEmpty(attrIds)) {
            attrEntities = this.listByIds(attrIds);
        }
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(List<AttrGroupRelationDelAndAddParam> param) {

        List<AttrAttrgroupRelationEntity> list = param.stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        attrAttrgroupRelationDao.deleteBatchRelation(list);
    }

    /**
     * 获取当前分组没有关联的所有属性
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {

        //当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //当前分组只能关联别的分组没有引用的属性
        //1，当前分类下的所有分组
        List<AttrGroupEntity> otherGroup = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));//.ne("attr_group_id", attrgroupId));
        List<Long> collect = otherGroup.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        //2，找到这些分组关联的属性
        List<Long> otherAttrId = null;
        if (CollectionUtils.isNotEmpty(collect)) {
            List<AttrAttrgroupRelationEntity> groupId = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
            otherAttrId = groupId.stream().map((item) -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
        }
        //3，从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", AttrTypeEnum.BAEE.getValue());
        if (CollectionUtils.isNotEmpty(otherAttrId)) {
            wrapper.notIn("attr_id", otherAttrId);
        }
        String key = KeyUtils.getKey(params);
        if (StringUtils.isNotBlank(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> findSearchAttrsIds(List<Long> attrIds) {
        List<AttrEntity> list = lambdaQuery().eq(AttrEntity::getSearchType, "1")
                .in(AttrEntity::getAttrId, attrIds).list();
        return list.stream().map(item -> item.getAttrId()).collect(Collectors.toList());
    }

}